var form, select, roleIdSelect;
var userId = getTempData('updateUserId');

$(function () {
    initLayUI(function () {
        initData();
        initButtons();
    });
});

function initLayUI(cb) {
    layui.use(['form', 'xmSelect'], function () {
        form = layui.form;
        select = layui.xmSelect;

        form.verify({
            userName: function (value) {
                if (value.length < 2 || value.length > 12) {
                    return '用户昵称必须2-12位长度';
                }
            },
            password: [
                /^[\S]{6,12}$/, '密码必须6到12位，且不能出现空格'
            ]
        });

        form.on('submit(userEditForm)', function (data) {
            let roleIds = roleIdSelect.getValue('value');
            if (roleIds.length === 0) {
                layerUtil.error("请至少选择一个角色");
                return false;
            }
            let user = {
                "loginAccount": data.field.loginAccount,
                "userName": data.field.userName,
                "email": data.field.email,
                "phone": data.field.phone,
                "gender": parseInt(data.field.gender),
                "roleIds": roleIds,
            };
            if (userId !== undefined) {
                user.userId = userId;
                updateUser(user);
            } else {
                addUser(user);
            }
            return false;
        });

        form.render();

        cb();
    });
}

function initButtons() {
    $("#cancelBtn").click(function () {
        layerUtil.closeLayer(parent.window.iframeIndex);
    });
}

function initData() {
    // 后续有时间可以替换成Promise
    initGenderData(function () {
        initRoleData(function () {
            initUserData();
        });
    });
}

function addUser(user) {
    ajaxUtil.simplePost(user, "/user/add", function () {
        layerUtil.closeLayer();
        reloadParentTable('userTable');
    });
}

function updateUser(user) {
    ajaxUtil.simplePost(user, "/user/update", function () {
        layerUtil.closeLayer();
        reloadParentTable('userTable');
    });
}

function initGenderData(cb) {
    ajaxUtil.loadDict("sys_user_gender", function (data) {
        data.forEach(function (item) {
            let radioStr = "<input type='radio' name='gender' value='" + item.dictValue + "'";
            if (item.isDefault) {
                radioStr += " checked ";
            }
            radioStr += " title='" + item.dictLabel + "'/>";
            $("#genderDiv").append(radioStr);
        });

        form.render();

        cb();
    });
}

function initRoleData(cb) {
    ajaxUtil.simplePost({page: 1, limit: 10, isEnabled: 1},
        "/role/list", function (data) {
            let arr = [];
            for (let i = 0; i < data.length; i++) {
                arr.push({
                    "name": data[i].roleName,
                    "value": data[i].roleId
                })
            }

            roleIdSelect = select.render({
                el: '#roleIds',
                toolbar: {
                    show: true,
                    list: ['ALL', 'REVERSE', 'CLEAR']
                },
                data: arr
            });

            cb();
        }, 0, 0)
}

function initUserData() {
    if (userId !== undefined) {
        ajaxUtil.simpleGet("/user/queryUserById?userId=" + userId, function (data) {
            form.val('form', {
                "loginAccount": data.loginAccount,
                "userName": data.userName,
                "email": data.email,
                "phone": data.phone,
                "gender": data.gender,
                "password": data.password
            });
            // 多选选中
            roleIdSelect.setValue(data.roleIds);
        });
    }
}